<template>
    <div style="margin-top: 10px; margin-left: 10px; margin-right: 10px" class="inlineClass">
        <el-form :inline="true" :model="searchData">
            <el-form-item label="接口服务编码">
                <el-input v-model="searchData.apiServiceCode" placeholder="服务编码" clearable />
            </el-form-item>
            <el-form-item label="接口服务名称">
                <el-input v-model="searchData.apiServiceName" placeholder="接口服务名称" clearable />
            </el-form-item>
            <el-form-item label="接口服务地址">
                <el-input v-model="searchData.apiServiceUrl" placeholder="接口服务地址" clearable />
            </el-form-item>
            <el-form-item label="所属服务">
                <el-select v-model="searchData.applicationId" placeholder="所属服务" clearable>
                    <el-option :label="item.applicationName" :value="item.id" v-for="item in applicationList" :key="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :loading="searchLoading" icon="SearchOutlined" @click="queryPage">搜 索</el-button>
                <el-button icon="ReloadOutlined" @click="resetParam">重 置</el-button>
            </el-form-item>
        </el-form>

        <div style="margin-top: 20px"></div>

        <div>
            <el-button type="primary" :loading="searchLoading" icon="PlusOutlined" @click="addDialog">添加接口服务模板</el-button>
        </div>

        <div style="margin-bottom: 20px"></div>

        <el-table
            :data="pageList"
            style="width: 100%; margin-bottom: 20px; margin-top: 20px;"
            row-key="id"
            border
            :stripe="true"
            :show-overflow-tooltip="true"
            max-height="80vh"
        >
            <el-table-column prop="apiServiceCode" label="接口服务编码" />
            <el-table-column prop="apiServiceName" label="接口服务名称" />
            <el-table-column prop="apiServiceUrl" label="接口服务地址" />
            <el-table-column prop="apiServiceType" label="接口服务类型" />
            <el-table-column prop="apiServiceMethod" label="接口服务方法" />
            <el-table-column prop="applicationName" label="所属服务" />

            <el-table-column align="center">
                <template #header>
                    <span>操 作</span>
                </template>
                <template #default="scope">
                    <el-button size="small" type="success" @click="handleUpdate(scope.$index, scope.row)">修 改</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)">删 除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :small="false"
            :background="true"
            layout="prev, pager, next, jumper, sizes, total"
            :total="total"
            @change="changePage"
            :page-sizes="[10, 20, 30, 50]"
            style="float: right"
        />

        <el-dialog
            v-model="addDialogFlag"
            title="添加接口服务模板"
            width="40%"
            align-center
            :show-close="false"
            :close-on-click-modal="false"
        >
            <div class="formContainer">
                <el-form :model="apiServiceForm" :rules="apiServiceRules" ref="apiServiceFormRef">
                    <el-form-item label="接口模板编码" label-width="20%" prop="apiServiceCode">
                        <el-input v-model="apiServiceForm.apiServiceCode" placeholder="接口模板编码" clearable />
                    </el-form-item>
                    <el-form-item label="接口模板名称" label-width="20%" prop="apiServiceName">
                        <el-input v-model="apiServiceForm.apiServiceName" placeholder="接口模板名称" clearable />
                    </el-form-item>
                    <el-form-item label="所属服务" label-width="20%" prop="applicationId">
                        <el-select v-model="apiServiceForm.applicationId" placeholder="所属服务" clearable>
                            <el-option :label="item.applicationName" :value="item.id" v-for="item in applicationList" :key="item.id"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="接口模板类型" label-width="20%" prop="apiServiceType">
                        <el-radio-group v-model="apiServiceForm.apiServiceType">
                            <el-radio label="MSSA">微服务共享API</el-radio>
                            <el-radio label="MSOA">微服务自有API</el-radio>
                            <el-radio label="RTSA">通用透传API</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="接口模板方法" label-width="20%" prop="apiServiceMethod">
                        <el-radio-group v-model="apiServiceForm.apiServiceMethod">
                            <el-radio label="GET">GET请求</el-radio>
                            <el-radio label="POST">POST请求</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="接口模板地址" label-width="20%" prop="apiServiceUrl">
                        <el-input v-model="apiServiceForm.apiServiceUrl" placeholder="接口模板地址" clearable />
                    </el-form-item>
                    <el-form-item label="接口模板请求参数" label-width="20%" prop="apiServiceRequestContentList">
                        <el-button type="primary" class="addCollapse" @click="addRequestVariable()">添加请求入参</el-button>
                        <el-form label-width="auto" style="width: 100%">
                            <el-collapse>
                                <el-collapse-item :name="paramIndex" v-for="(paramItem, paramIndex) in apiServiceForm.apiServiceRequestContentList">
                                    <template #title>
                                        <div class="collapseTitle">
                                            <span>参数 {{(paramIndex + 1)}}</span>
                                            <el-button type="danger" plain size="small" style="margin-left: 20px" @click.stop="deleteRequestVariable(paramIndex)">删除</el-button>
                                        </div>
                                    </template>
                                    <el-form-item label="参数类型">
                                        <el-radio-group v-model="paramItem.type">
                                            <el-radio label="custom">自定义</el-radio>
                                            <el-radio label="variable">关联变量</el-radio>
                                            <el-radio label="urlQuery">URL地址变量</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                    <el-form-item label="参数名称">
                                        <el-input v-model="paramItem.variableName" style="width: 100%; margin-bottom: 10px"/>
                                    </el-form-item>
                                    <el-form-item label="参数值" v-if="paramItem.type === 'custom'">
                                        <el-input v-model="paramItem.variableValue" style="width: 100%">
                                            <template #prepend>
                                                <el-select v-model="paramItem.variableType" placeholder="Select" style="width: 115px">
                                                    <el-option label="字符串" value="String" />
                                                    <el-option label="数组" value="Array" />
                                                    <el-option label="对象" value="Object" />
                                                </el-select>
                                            </template>
                                        </el-input>
                                    </el-form-item>

                                    <el-form-item label="URL地址参数名称" v-if="paramItem.type === 'urlQuery'">
                                        <el-input v-model="paramItem.variableValue" style="width: 100%" />
                                    </el-form-item>
                                </el-collapse-item>
                            </el-collapse>
                        </el-form>
                    </el-form-item>
                    <el-form-item label="接口模板响应参数" label-width="20%" prop="apiServiceResponseContentList">
                        <el-button type="primary" class="addCollapse" @click="addResponseVariable">添加响应出参映射</el-button>

                        <el-form label-width="auto" style="width: 100%" >
                            <el-collapse>
                                <el-collapse-item :name="paramIndex" v-for="(paramItem, paramIndex) in apiServiceForm.apiServiceResponseContentList">
                                    <template #title>
                                        <div class="collapseTitle">
                                            <span>参数 {{(paramIndex + 1)}}</span>
                                            <el-button type="danger" plain size="small" style="margin-left: 20px" @click.stop="deleteResponseVariable(paramIndex)">删除</el-button>
                                        </div>
                                    </template>

                                    <el-form-item label="参数值">
                                        <el-input v-model="paramItem.variableValue" style="width: 100%" placeholder="参数值jsonPath"/>
                                    </el-form-item>
                                </el-collapse-item>
                            </el-collapse>
                        </el-form>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancelDialog()">取 消</el-button>
                    <el-button type="primary" :loading="saveLoading" @click="submitDialog(apiServiceFormRef)">
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>


        <el-dialog
            v-model="deleteDialogFlag"
            title="删除接口服务模板"
            width="20%"
            align-center
            :show-close="false"
            :close-on-click-modal="false"
        >
            <span>是否确认删除？</span>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancelDeleteDialog()">取 消</el-button>
                    <el-button type="primary" :loading="deletaLoading" @click="submitDeleteDialog()">
                        提 交
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {useRoute} from "vue-router";
import {createTag} from "@/utils/ywuCommon";
import {ref} from "vue";
import {addApiServiceInfo, apiServiceInfoQuery, deleteApiServiceInfo, updateApiServiceInfo} from "@/request/apiService";
import {ElNotification, FormInstance} from "element-plus";
import {applicationInfoQuery} from "@/request/service";

let route = useRoute();
createTag(route);

let pageList = ref([]);
let pageNum = ref(1);
let pageSize = ref(10);
let total = ref(0)
let searchLoading = ref(false);
let addDialogFlag = ref(false);
let saveLoading = ref(false);
let deleteDialogFlag = ref(false);
let deletaLoading = ref(false);
let apiServiceFormRef = ref<FormInstance>();
let applicationList = ref([])
let apiServiceForm = ref({
    id: "",
    apiServiceCode: "",
    apiServiceName: "",
    apiServiceUrl: "",
    applicationId: "",
    apiServiceType: "",
    apiServiceMethod: "",
    apiServiceRequestContentList: [],
    apiServiceResponseContentList: [],
    apiServiceRequestContent: "",
    apiServiceResponseContent: ""
});

let searchData = ref({
    id: "",
    apiServiceCode: "",
    apiServiceName: "",
    apiServiceUrl: "",
    applicationId: ""
});

let apiServiceRules = ref({
    apiServiceCode: [{ required: true, message: '接口模板编码不能为空', trigger: 'blur' }],
    apiServiceName: [{ required: true, message: '接口模板名称不能为空', trigger: 'blur' }],
    apiServiceUrl: [{ required: true, message: '接口模板类型不能为空', trigger: 'blur' }],
    apiServiceType: [{ required: true, message: '接口模板方法不能为空', trigger: 'blur' }],
    apiServiceMethod: [{ required: true, message: '接口模板地址不能为空', trigger: 'blur' }],
    applicationId: [{ required: true, message: '所属服务不能为空', trigger: 'blur' }],
});

// 查询应用列表
let apiSearchData = {
    pageInfo: {
        pageIndex: 1,
        pageSize: 1000
    }
}
applicationInfoQuery(apiSearchData).then(res => {
    if (res["code"] === '200') {
        for (let i = 0; i < res.data.length; i++) {
            res.data[i].id = res.data[i].id + "";
        }
        applicationList.value = res.data;
    }
})

function queryPage() {
    searchLoading.value = true;
    let param = {
        pageInfo: {
            pageIndex: pageNum.value,
            pageSize: pageSize.value
        },
        apiServiceCode: searchData.value.apiServiceCode,
        apiServiceName: searchData.value.apiServiceName,
        apiServiceUrl: searchData.value.apiServiceUrl,
        applicationId: searchData.value.applicationId
    }
    apiServiceInfoQuery(param).then(res => {
        pageList.value = res.data.dataList;
        for (let i = 0; i < pageList.value.length; i++) {
            pageList.value[i].apiServiceRequestContentList = JSON.parse(pageList.value[i].apiServiceRequestContent);
            pageList.value[i].apiServiceResponseContentList = JSON.parse(pageList.value[i].apiServiceResponseContent);
        }
        pageNum.value = res.data.pageIndex;
        pageSize.value = res.data.pageSize;
        total.value = res.data.recordCount;
        searchLoading.value = false;
    }).catch(error => {
        searchLoading.value = false;
    })
}

queryPage();

function resetParam() {
    searchData.value = {
        id: "",
        apiServiceCode: "",
        apiServiceName: "",
        apiServiceUrl: "",
        applicationId: ""
    }
}

function resetFormParam() {
    apiServiceForm.value = {
        id: "",
        apiServiceCode: "",
        apiServiceName: "",
        apiServiceUrl: "",
        applicationId: "",
        apiServiceType: "",
        apiServiceMethod: "",
        apiServiceRequestContentList: [],
        apiServiceResponseContentList: [],
        apiServiceRequestContent: "",
        apiServiceResponseContent: ""
    }
}

function handleUpdate(index, row) {
    addDialogFlag.value = true;
    apiServiceForm.value = {
        id: row.id,
        apiServiceCode: row.apiServiceCode,
        apiServiceName: row.apiServiceName,
        apiServiceUrl: row.apiServiceUrl,
        applicationId: row.applicationId,
        apiServiceType: row.apiServiceType,
        apiServiceMethod: row.apiServiceMethod,
        apiServiceRequestContentList: row.apiServiceRequestContentList,
        apiServiceResponseContentList: row.apiServiceResponseContentList,
        apiServiceRequestContent: row.apiServiceRequestContent,
        apiServiceResponseContent: row.apiServiceResponseContent
    }
}

function handleDelete(index, row) {
    deleteDialogFlag.value = true;
    apiServiceForm.value.id = row.id;
}

function changePage(index, size) {
    let param = {
        pageInfo: {
            pageIndex: index,
            pageSize: size
        },
        apiServiceCode: searchData.value.apiServiceCode,
        apiServiceName: searchData.value.apiServiceName,
        apiServiceUrl: searchData.value.apiServiceUrl,
        applicationId: searchData.value.applicationId
    }
    apiServiceInfoQuery(param).then(res => {
        pageList.value = res.data.dataList;
        for (let i = 0; i < pageList.value.length; i++) {
            pageList.value[i].apiServiceRequestContentList = JSON.parse(pageList.value[i].apiServiceRequestContent);
            pageList.value[i].apiServiceResponseContentList = JSON.parse(pageList.value[i].apiServiceResponseContent);
        }
        pageNum.value = res.data.pageIndex;
        pageSize.value = res.data.pageSize;
        total.value = res.data.recordCount;
        searchLoading.value = false;
    }).catch(error => {
        searchLoading.value = false;
    })
}

function addDialog() {
    resetFormParam()
    addDialogFlag.value = true;
}

function cancelDialog() {
    addDialogFlag.value = false;
}

function submitDialog(formEl: FormInstance | undefined) {
    if (!formEl) return
    saveLoading.value = true
    formEl.validate((valid) => {
        if (valid) {
            apiServiceForm.value.apiServiceRequestContent = JSON.stringify(apiServiceForm.value.apiServiceRequestContentList)
            apiServiceForm.value.apiServiceResponseContent = JSON.stringify(apiServiceForm.value.apiServiceResponseContentList)
            if (apiServiceForm.value.id !== '') {
                // 修改
                updateApiServiceInfo(apiServiceForm.value).then(res => {
                    if (res["code"] === '200') {
                        ElNotification({
                            title: 'Success',
                            message: res["message"],
                            type: 'success'
                        })
                        let param = {
                            pageInfo: {
                                pageIndex: pageNum.value,
                                pageSize: pageSize.value
                            },
                            apiServiceCode: searchData.value.apiServiceCode,
                            apiServiceName: searchData.value.apiServiceName,
                            apiServiceUrl: searchData.value.apiServiceUrl,
                            applicationId: searchData.value.applicationId
                        }
                        apiServiceInfoQuery(param).then(res => {
                            pageList.value = res.data.dataList;
                            for (let i = 0; i < pageList.value.length; i++) {
                                pageList.value[i].apiServiceRequestContentList = JSON.parse(pageList.value[i].apiServiceRequestContent);
                                pageList.value[i].apiServiceResponseContentList = JSON.parse(pageList.value[i].apiServiceResponseContent);
                            }
                            pageNum.value = res.data.pageIndex;
                            pageSize.value = res.data.pageSize;
                            total.value = res.data.recordCount;
                        })
                        saveLoading.value = false
                        addDialogFlag.value = false
                    }
                }).catch(res => {
                    saveLoading.value = false
                })
            } else {
                // 调用后端接口插入数据
                addApiServiceInfo(apiServiceForm.value).then(res => {
                    if (res["code"] === '200') {
                        ElNotification({
                            title: 'Success',
                            message: res["message"],
                            type: 'success'
                        })
                        let param = {
                            pageInfo: {
                                pageIndex: pageNum.value,
                                pageSize: pageSize.value
                            },
                            apiServiceCode: searchData.value.apiServiceCode,
                            apiServiceName: searchData.value.apiServiceName,
                            apiServiceUrl: searchData.value.apiServiceUrl,
                            applicationId: searchData.value.applicationId
                        }
                        apiServiceInfoQuery(param).then(res => {
                            pageList.value = res.data.dataList;
                            for (let i = 0; i < pageList.value.length; i++) {
                                pageList.value[i].apiServiceRequestContentList = JSON.parse(pageList.value[i].apiServiceRequestContent);
                                pageList.value[i].apiServiceResponseContentList = JSON.parse(pageList.value[i].apiServiceResponseContent);
                            }
                            pageNum.value = res.data.pageIndex;
                            pageSize.value = res.data.pageSize;
                            total.value = res.data.recordCount;
                        })
                    }
                    saveLoading.value = false
                    addDialogFlag.value = false
                }).catch(res => {
                    saveLoading.value = false
                })
            }
        } else {
            ElNotification({
                title: 'Error',
                message: '请填写必填项',
                type: 'error'
            })
            saveLoading.value = false
        }
    })
}


function addRequestVariable() {
    if (!apiServiceForm.value.apiServiceRequestContentList) {
        apiServiceForm.value.apiServiceRequestContentList = []
    }
    let variableInfo = {variableName: "", variableValue: "", type: "custom", variableType: "String", variableParamName: ""}
    apiServiceForm.value.apiServiceRequestContentList.push(variableInfo)
}

function deleteRequestVariable(paramIndex) {
    apiServiceForm.value.apiServiceRequestContentList.splice(paramIndex, 1);
}

function addResponseVariable() {
    if (!apiServiceForm.value.apiServiceResponseContentList) {
        apiServiceForm.value.apiServiceResponseContentList = []
    }
    let variableInfo = {variableName: "", variableValue: ""}
    apiServiceForm.value.apiServiceResponseContentList.push(variableInfo)
}

function deleteResponseVariable(paramIndex) {
    apiServiceForm.value.apiServiceResponseContentList.splice(paramIndex, 1);
}

function cancelDeleteDialog() {
    deleteDialogFlag.value = false
}

function submitDeleteDialog() {
    deletaLoading.value = true
    let param = {
        id: apiServiceForm.value.id
    }
    deleteApiServiceInfo(param).then(res => {
        if (res["code"] === '200') {
            ElNotification({
                title: 'Success',
                message: res["message"],
                type: 'success'
            })
            let param = {
                pageInfo: {
                    pageIndex: pageNum.value,
                    pageSize: pageSize.value
                },
                apiServiceCode: searchData.value.apiServiceCode,
                apiServiceName: searchData.value.apiServiceName,
                apiServiceUrl: searchData.value.apiServiceUrl,
                applicationId: searchData.value.applicationId
            }
            apiServiceInfoQuery(param).then(res => {
                pageList.value = res.data.dataList;
                for (let i = 0; i < pageList.value.length; i++) {
                    pageList.value[i].apiServiceRequestContentList = JSON.parse(pageList.value[i].apiServiceRequestContent);
                    pageList.value[i].apiServiceResponseContentList = JSON.parse(pageList.value[i].apiServiceResponseContent);
                }
                pageNum.value = res.data.pageIndex;
                pageSize.value = res.data.pageSize;
                total.value = res.data.recordCount;
            })
        }
        deleteDialogFlag.value = false
        deletaLoading.value = false
    }).catch(res => {
        deletaLoading.value = false
    })
}
</script>

<style scoped>
.inlineClass ::v-deep .el-form-item__content {
    width: 250px;
}
</style>